<template>
  <div class="right">
    <div class="nav-title"><span></span>
      <p>用户管理</p>
    </div>
    <div class="dataList">
      <div class="from">
        <el-form
          :inline="true"
          class="demo-form-inline"

        >
          <el-form-item label="用户名称">
            <el-input
              v-model="realNm"
              placeholder="请输入用户名称"
            ></el-input>
          </el-form-item>
          <el-form-item label="所在地区">

            <el-cascader
              size="medium"
              :options="options"
              change-on-select
              v-model="adcd"
              :props="propsDefine"
            ></el-cascader>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              @click="queryHandler"
            >查询</el-button>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              style="float:right;"
              @click="addHandler"
            >新增</el-button>
          </el-form-item>
        </el-form>
      </div>
      <!-- <div > -->

        <el-table
          :data="dataList"
          border
          v-loading='loading'
        >
          <el-table-column
            type="index"
            label="序号"
            width="50"
            align="center"
          >
          </el-table-column>
          <el-table-column
            prop="REALNAME"
            label="用户名称"
            width="100"
            align="center"
          >
          </el-table-column>
          <el-table-column
           prop="UNAME"
            align="center"
            show-overflow-tooltip
            label="登录账号"
            width="120">
            <!-- UNAME -->
          </el-table-column>
          <el-table-column
            prop="roleNm"
            align="center"
              show-overflow-tooltip
            :formatter="getUserRole"
            label="用户角色"

          >
          </el-table-column>
          <el-table-column
            prop="ADNM"
            align="center"

            width="120"
            show-overflow-tooltip
            label="所在地区"
          >
          </el-table-column>
          <el-table-column
            prop="CELLPHONE"
            align="center"
            width="120"
            show-overflow-tooltip
            label="手机号码"
          >
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            width="250"
          >
            <template slot-scope="scope">
              <el-button
                @click="grantHandler(scope.row)"
                type="primary"
                size="small"
              >分配角色</el-button>
              <el-button
                @click="editHandler(scope.row)"
                type="warning"
                size="small"
              >编辑</el-button>
              <el-button
                @click='deleteUser(scope.row)'
                type="danger"
                size="small"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      <!-- </div> -->

      <!-- 分页 -->
      <div class="block">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
      <!-- 分配角色 -->
      <div>
        <el-dialog
          title="分配角色"
          :visible.sync="dialogGrantVisible"
        >
          <el-form
            :model="grantRoles"
            ref="grantForm"
            :rules='rules'
          >

            <el-form-item
              label="用户名称"
              :label-width="formLabelWidth"
            >
              <el-input
                :disabled="true"
                v-model="grantRoles.REALNAME"
                autocomplete="off"
              ></el-input>
            </el-form-item>
            <el-form-item
              label="选择角色"
              :label-width="formLabelWidth"
            >
              <el-select
                v-model="roleVals"
                multiple
                placeholder="请选择"
                size='medium'
              >
                <el-option
                  v-for="item in roles"
                  :key="item.ROLEID"
                  :label="item.NAME"
                  :value="item.ROLEID"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-form>
          <div
            slot="footer"
            class="dialog-footer"
          >
            <el-button @click="dialogGrantVisible = false">取 消</el-button>
            <el-button
              type="primary"
              @click="submitRoles4Grant"
            >确 定</el-button>
          </div>
        </el-dialog>
      </div>
      <!-- 编辑用户 -->
      <div>
        <el-dialog
          title="编辑用户"
          :visible.sync="dialogEditVisible"
        >
          <el-form
            :model="euser"
            ref="userform4Edit"
            :rules='rules'
          >
            <el-form-item
              label="用户账号"
              :label-width="formLabelWidth"
            >
              <el-input
                :disabled="true"
                v-model="euser.uname"
                autocomplete="off"
              ></el-input>
            </el-form-item>
            <el-form-item
              label="用户名称"
              :label-width="formLabelWidth"
            >
              <el-input
                v-model="euser.realname"
                autocomplete="off"
              ></el-input>
            </el-form-item>
            <el-form-item
              label="手机号码"
              :label-width="formLabelWidth"
            >
              <el-input
                v-model="euser.phone"
                autocomplete="off"
              ></el-input>
            </el-form-item>
            <el-form-item
              label="所在地区"
              prop='areaid'
              :label-width="formLabelWidth"
            >
              <el-cascader
                size="medium"
                :options="options"
                change-on-select
                v-model="euser.areaid"
                :props="propsDefine"
              ></el-cascader>

            </el-form-item>
            <el-form-item
              prop='unitid'
              label="所在单位"
              :label-width="formLabelWidth"
            >
              <el-cascader
                size="medium"
                :options="options2"
                change-on-select
                v-model="euser.unitid"
                :props="propsDefine2"
              ></el-cascader>
            </el-form-item>
          </el-form>
          <div
            slot="footer"
            class="dialog-footer"
          >
            <el-button @click="dialogEditVisible = false">取 消</el-button>
            <el-button
              type="primary"
              @click="submitUser4Edit"
            >确 定</el-button>
          </div>
        </el-dialog>
      </div>
      <!-- 新增用户 -->
      <div>

        <el-dialog
          title="新增用户"
          :visible.sync="dialogAddVisible"
        >
          <el-form
            :model="auser"
            ref="userform4Add"
            :rules='rules'
          >
            <el-form-item
              label="用户账号"
              prop='uname'
              :label-width="formLabelWidth"
            >
              <el-input
                v-model="auser.uname"
                autocomplete="off"
              ></el-input>
            </el-form-item>
            <el-form-item
              label="密码"
              prop='password'
              :label-width="formLabelWidth"
            >
              <el-input
              type="password"
                v-model="auser.password"
                autocomplete="off"
              ></el-input>
            </el-form-item>
            <el-form-item
              label="确认密码"
              prop='checkPass'

              :label-width="formLabelWidth"
            >
              <el-input
               type="password"
                v-model="auser.checkPass"
                autocomplete="off"
              ></el-input>
            </el-form-item>
            <el-form-item
              prop='realname'
              label="用户名称"
              :label-width="formLabelWidth"
            >
              <el-input
                v-model="auser.realname"
                autocomplete="off"
              ></el-input>
            </el-form-item>
            <el-form-item
              label="手机号码"
              prop='phone'
              :label-width="formLabelWidth"
            >
              <el-input
                v-model="auser.phone"
                autocomplete="off"
              ></el-input>
            </el-form-item>
            <el-form-item
              prop='areaid'
              label="所在地区"
              :label-width="formLabelWidth"
               :rules="[{required: true,   trigger: 'change'  }]"
            >
              <el-cascader
                v-model="auser.areaid"
                size="medium"
                :options="options"
                change-on-select
                :props="propsDefine"
              ></el-cascader>
            </el-form-item>
            <el-form-item
              label="所在单位"
              prop='unitid'
              :label-width="formLabelWidth"
              :rules='[
          { required: true,  trigger: "change" }
        ]'
            >
              <el-cascader
                v-model="auser.unitid"
                size="medium"
                :options="options1"
                change-on-select
                :props="propsDefine1"
              ></el-cascader>
            </el-form-item>
          </el-form>
          <div
            slot="footer"
            class="dialog-footer"
          >
            <el-button @click="dialogAddVisible = false">取 消</el-button>
            <el-button
              type="primary"
              @click="submitUser4Add"
            >确 定</el-button>
          </div>
        </el-dialog>
      </div>
    </div>
  </div>
</template>
<script>
import {getPidArr} from '@/components/utils/index.js'
import {
  userList,
  saveUser,
  postRolesList,
  grantRoles,
  adcdList,
  admaList,
  editUser,
  delUser
} from "@/components/api/api.js";
export default {
  data() {
    var validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else {
        if (this.auser.checkPass !== "") {
          this.$refs.userform4Add.validateField("checkPass");
        }
        callback();
      }
    };
    var validatePass2 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.auser.password) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    var validatePass5 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入手机号"));
      } else if(!/^[1][3,4,5,7,8][0-9]{9}$/.test(value)){
        callback(new Error("请输入正确格式手机号"));
      }else {
        callback();
      }
    };
    return {
      // unitids: [],
      unitids2: [],
      propsDefine: {
        value: "id",
        label: "text",
        children: "children"
      },
      propsDefine1: {
        value: "id",
        label: "text",
        children: "children"
      },
      propsDefine2: {
        value: "id",
        label: "text",
        children: "children"
      },
      options: [],
      options1: [],
      options2: [],

      roleVals: [],
      roles: [],
      currentUser: "",
      grantRoles: {
        userId: "",
        roleId: ""
      },
      realNm: "",
      adcd: [],
      adcd1: [],
      // adcd2: [],
      obj: {},
      auser: {
        uname: "", //   用户名
        password: "", //   密码
        checkPass: "",
        realname: "", //  昵称
        phone: "", //  电话
        areaid: [],
        unitid: [] //   地区编码
      },
      euser: {
        uname: "",
        realname: "",
        phone: "",
        areaid: [],
        uid: "",
        userid: ""
      },
      qurUser: {
        roleNm: "",
        realName: "",
        adNm: "",
        telPhone: "",
        uAddress: ""
      },
      dialogAddVisible: false,
      dialogGrantVisible: false,
      formData: {
        // 传给后台的id
        inspectObject: "",
        // 输入框显示的
        inspectObjectName: ""
      },
      // 是否显示巡检对象的树状选择器
      isShowSelect: false,
      // 巡检对象的选项数据
      inspectionObjectOptions: [],
      // 巡检对象的选项的配置参数
      defaultProps: {
        id: "id",
        label: "departName",
        children: "children"
      },
      treeData: [],
      currentPage: 1,
      dialogEditVisible: false,
      rules: {
        uname: [{ required: true, message: "请输入用户账号", trigger: "blur" }],
        realname: [
          { required: true, message: "请输入用户名称", trigger: "blur" }
        ],
        password: [
          { required: true, validator: validatePass, trigger: "blur" }
        ],
        checkPass: [
          { required: true, validator: validatePass2, trigger: "blur" }
        ],
        phone: [
          { required: true, validator: validatePass5, trigger: "blur" }
        ],
      },
      formLabelWidth: "120px",
      tableData: [],
      dataList: [],
      loading: true,
      pagesize: 10,
      total: 0
    };
  },
  methods: {
    // 给用户分配角色权限
    grantHandler(row) {
      this.currentUser = row.USERID;
      this.grantRoles.REALNAME = row.REALNAME;
      postRolesList()
        .then(res => {
          if (!res.result) return false;
          this.roles = res.result;
        })
        .then(res => {
          this.roleVals = row.roles.map(item => {
            return item.ROLEID.trim();
          });
        });
      this.dialogGrantVisible = true;
    },
    submitRoles4Grant() {
      this.$refs["grantForm"].validate(valid => {
        if (valid) {
          // 提交表单
          grantRoles({ userId: this.currentUser, roleId: this.roleVals }).then(
            res => {
              if (res.result === 1) {
                // 关闭窗口
                this.$message({
                  type: "success",
                  message: "分配角色成功"
                });
                this.dialogGrantVisible = false;
                // 刷新列表
                this.initList();
              }
            }
          );
        }
      });
    },
    addHandler() {
      this.auser={
        uname: "", //   用户名
        password: "", //   密码
        checkPass: "",
        realname: "", //  昵称
        phone: "", //  电话
        areaid: [],
        unitid: [] //
      }
      this.dialogAddVisible = true;
      // document.getElementsByClassName('el-cascader__label')[2].innerText = '';
      // document.getElementsByClassName('el-cascader__label')[1].innerText = '';
       if (this.$refs["userform4Add"] !== undefined) {
        this.$refs["userform4Add"].resetFields();
      }
    },
    submitUser4Add() {
      let _this=this;
      this.$refs["userform4Add"].validate(valid => {
        if (valid) {
          // 提交表单
          _this.auser.areaid = _this.auser.areaid[_this.auser.areaid.length - 1];
          _this.auser.unitid = _this.auser.unitid[_this.auser.unitid.length - 1];
          delete _this.auser.checkPass;
          saveUser(_this.auser).then(res => {
            if (res.result === 1) {
              // 关闭窗口
              this.dialogAddVisible = false;
              // 刷新列表
              this.initList();
              this.$message({
                type: "success",
                message: "新增成功!"
              });
            }
          this.auser.areaid = [];
          this.auser.unitid = [];

          });
        }
      });

    },
    editHandler(row) {

      console.log(row)
      console.log(this.options2)
      this.euser.uname = row.UNAME;
      this.euser.realname = row.REALNAME;
      this.euser.phone = row.CELLPHONE;
      this.euser.areaid = getPidArr(this.options,row.ADCD).reverse();
      this.euser.uid = row.U_ID;
      this.euser.userid = row.USERID;
      this.euser.unitid = getPidArr(this.options2,row.UNITID).reverse();
      // 修改弹窗
      this.dialogEditVisible = true;
      console.log(this.euser.unitid)
    },
    submitUser4Edit() {
      this.$refs["userform4Edit"].validate(valid => {
        if (valid) {
          // 提交表单
          this.euser.areaid = this.euser.areaid[this.euser.areaid.length - 1];
          this.euser.unitid = this.euser.unitid[this.euser.unitid.length - 1];
          // console.log(this.auser)
          editUser(this.euser).then(res => {
            if (res.result === 1) {
              // 关闭窗口
              this.dialogEditVisible = false;
              // 刷新列表
              this.initList();
              this.$message({
                type: "success",
                message: "编辑成功!"
              });
            }
          });
        }
      });
    },
    deleteUser(row) {
      // 点击删除弹窗
      this.$confirm("此操作将永久删除该用户, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          // 删除用户
          console.log(row)
          delUser({ uids: [row.U_ID], userids: [row.USERID] }).then(res => {
            if (res.result === 1) {
              this.initList();
              this.$message({
                type: "success",
                message: "删除成功!"
              });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    // 查询操作
    queryHandler() {
      this.currentPage = 1;
      let aa = this.adcd[this.adcd.length - 1];
      this.obj = { realname: this.realNm, adcd: aa };
      this.initList(this.obj);
      // this.adcd =[];
    },
    // 选择一页条数
    handleSizeChange(val) {
      this.pagesize = val;
      this.initList();
    },
    // 选择当前页
    handleCurrentChange(val) {
      this.currentPage = val;
      this.initList();
    },
    // 格式化角色数据
    getUserRole(row, column, cellValue, index) {
      let res = [];
      for (let i = 0; i < row.roles.length; i++) {
        res.push(row.roles[i].NAME);
      }
      return res.join("/");
    },
    // 初始化
    initList(obj) {
      userList(obj, {
        headers: {
          Rang: "max=" + this.currentPage + ";size=" + this.pagesize + ";",
          "Content-Type": "application/json"
        }
      })
        .then(res => {
          console.log(res.result)
          if (JSON.stringify(res.result) == "{}") {
            this.dataList = [];
            this.total = 0;
          } else {
            this.dataList = Object.values(res.result);
            // this.total = res.paging.total;
          }

          this.loading = false;
        })
        .then(() => {
          adcdList().then(res => {
            this.options = [{ text: "全部", id: null, pid: null }];
            this.options.push(res.result);
          });
        });
    }
  },
  mounted() {
    this.initList();
    admaList().then(res => {
      if (!res.result) return false;
      this.options1.push(res.result);
      this.options2.push(res.result);
    });
  }
};
</script>

<style scoped>
.right {
  border: 1px solid #e7e7e7;
  box-shadow: 0 0 4px #e7e7e7;
  background: #fff;
  border-radius: 5px;
}
.nav-title {
  height: 50px;
  display: -ms-flexbox;
  display: flex;
  width: 98%;
  margin: 0 auto;
  -ms-flex-align: center;
  align-items: center;
  border-bottom: 1px solid #f0f0f0;
}
.nav-title span {
  display: inline-block;
  width: 0px;
  height: 18px;
  border-radius: 5px;
  border-left: 4px solid #3380f3;
}
.nav-title p {
  padding-left: 10px;
  font-weight: 600;
}
.dataList {
  padding: 10px;
  /* height: 610px; */
}
.from {
  height: 50px;
}
.from .el-form-item:last-child {
  position: absolute;
  right: 0.3rem;
}
.el-table {
  height: 400px;
  overflow: auto;
}
.el-pagination {
  margin-top: 0.1rem;
  text-align: center;
}
.el-cascader {
  width: 100%;
}
</style>

